package cn.net.susan.job;

import cn.net.susan.entity.common.CommonNotifyConditionEntity;
import cn.net.susan.entity.common.CommonNotifyEntity;
import cn.net.susan.mapper.common.CommonNotifyMapper;
import cn.net.susan.util.FillUserUtil;
import cn.net.susan.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 消息通知job
 *
 * @author 苏三，该项目是知识星球：java突击队 的内部项目
 * @date 2024/2/6 上午11:23
 */
@Slf4j
@Component
public class CommonNotifyJob {

    @Autowired
    private CommonNotifyMapper commonNotifyMapper;


    /**
     * 定时执行
     */
    @Scheduled(fixedRate = 1000)
    public void run() {
        CommonNotifyConditionEntity conditionEntity = new CommonNotifyConditionEntity();
        conditionEntity.setIsPush(0);
        conditionEntity.setIsDel(0);
        List<CommonNotifyEntity> commonNotifyEntities = commonNotifyMapper.searchByCondition(conditionEntity);
        if (CollectionUtils.isEmpty(commonNotifyEntities)) {
            log.info("==没有通知需要推送==");
            return;
        }

        for (CommonNotifyEntity commonNotifyEntity : commonNotifyEntities) {
            pushNotify(commonNotifyEntity);
        }
    }


    private void pushNotify(CommonNotifyEntity commonNotifyEntity) {
        try {
            WebSocketServer.sendMessage(commonNotifyEntity);

            commonNotifyEntity.setIsPush(1);
            FillUserUtil.fillUpdateUserInfoFromCreate(commonNotifyEntity);
            commonNotifyMapper.update(commonNotifyEntity);
        } catch (IOException e) {
            log.error("WebSocket通知推送失败，原因：", e);
        }
    }
}
